package com.unionfetch.content_home.ui.step

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.widget.addTextChangedListener
import com.alibaba.android.arouter.launcher.ARouter
import com.unionfetch.content_home.HomeConstants.STR.EUR
import com.unionfetch.content_home.HomeConstants.STR.GBP
import com.unionfetch.content_home.HomeConstants.STR.USC
import com.unionfetch.content_home.HomeConstants.STR.USD
import com.unionfetch.content_home.R
import com.unionfetch.content_home.bean.TradeAccountType
import com.unionfetch.content_home.bean.request.SecondStepRequest
import com.unionfetch.content_home.bean.request.ThirdStepIbRequest
import com.unionfetch.content_home.bean.request.ThirdStepRequest
import com.unionfetch.content_home.bean.request.full
import com.unionfetch.content_home.bean.request.fullThirdStep
import com.unionfetch.content_home.contract.OpenAccountContract
import com.unionfetch.content_home.presenter.OpenAccountPresenter
import com.unionfetch.content_home.ui.dialog.CustomTipDialog
import com.unionfetch.content_home.ui.fragment.HomeFragment
import com.unionftech.common.R.color
import com.unionftech.common.R.dimen
import com.unionftech.common.R.drawable
import com.unionftech.common.R.string
import com.unionftech.common.base.IUpdate
import com.unionftech.common.base.mvp.annitation.InjectPresenter
import com.unionftech.common.base.mvp.impl.BaseMvpActivity
import com.unionftech.common.bean.ResponseResult
import com.unionftech.common.bean.toast
import com.unionftech.common.common.GlobalInfoManager
import com.unionftech.common.common.bean.SystemUserInfo
import com.unionftech.common.common.bean.TradePlatform
import com.unionftech.common.common.bean.UserGroupInfo
import com.unionftech.common.common.contract.CommonContract
import com.unionftech.common.common.language.DynamicResourceManager
import com.unionftech.common.common.presenter.CommonPresenter
import com.unionftech.common.router.RouterPath
import com.unionftech.common.utils.CheckInputUtil
import com.unionftech.common.utils.LogUtils
import com.unionftech.common.utils.ProtocolUtil
import com.unionftech.common.utils.RegexUtils
import com.unionftech.common.utils.SignUtils
import com.unionftech.common.utils.ToastUtils
import com.unionftech.common.utils.Utils
import com.unionftech.common.utils.autoSize
import com.unionftech.common.utils.expandTouchArea
import com.unionftech.common.utils.serializable

class ThirdStepOpenAccountActivity : BaseMvpActivity(), IUpdate, CommonContract.IPlatformView,
    CommonContract.ICurrencyView, CommonContract.IAccountTypeView,
    OpenAccountContract.IThirdStepView {

    private val mBtnConfirm by lazy { findViewById<Button>(R.id.btn_confirm) }
    private val mTvTradingAgreementElement by lazy { findViewById<TextView>(R.id.tv_trading_agreement_element) }
    private val mTvAgreementText by lazy { findViewById<TextView>(R.id.tv_agreement_text) }
    private val mIvAgreement by lazy { findViewById<ImageView>(R.id.iv_agreement) }
    private val mTvConfirmTradingPasswordError by lazy { findViewById<TextView>(R.id.tv_confirm_trading_password_error) }
    private val mIvClearConfirmTradingPassword by lazy { findViewById<ImageView>(R.id.iv_clear_confirm_trading_password) }
    private val mIvShowConfirmTradingPassword by lazy { findViewById<ImageView>(R.id.iv_show_confirm_trading_password) }
    private val mEtConfirmTradingPassword by lazy { findViewById<EditText>(R.id.et_confirm_trading_password) }
    private val mTvConfirmTradingPasswordTitle by lazy { findViewById<TextView>(R.id.tv_confirm_trading_password_title) }
    private val mTvTradingPasswordError by lazy { findViewById<TextView>(R.id.tv_trading_password_error) }
    private val mIvClearTradingPassword by lazy { findViewById<ImageView>(R.id.iv_clear_trading_password) }
    private val mIvShowTradingPassword by lazy { findViewById<ImageView>(R.id.iv_show_trading_password) }
    private val mEtTradingPassword by lazy { findViewById<EditText>(R.id.et_trading_password) }
    private val mTvTradingPasswordTitle by lazy { findViewById<TextView>(R.id.tv_trading_password_title) }
    private val mTvAccountCurrencyError by lazy { findViewById<TextView>(R.id.tv_account_currency_error) }
    private val mLlGbp by lazy { findViewById<LinearLayout>(R.id.ll_gbp) }
    private val mLlEur by lazy { findViewById<LinearLayout>(R.id.ll_eur) }
    private val mLlUsd by lazy { findViewById<LinearLayout>(R.id.ll_usd) }
    private val mLlUsc by lazy { findViewById<LinearLayout>(R.id.ll_usc) }
    private val mLlAccountCurrency by lazy { findViewById<LinearLayout>(R.id.ll_account_currency) }
    private val mTvWithoutCurrency by lazy { findViewById<TextView>(R.id.tv_without_currency) }
    private val mTvAccountCurrencyTitle by lazy { findViewById<TextView>(R.id.tv_account_currency_title) }
    private val mTvAccountTypeError by lazy { findViewById<TextView>(R.id.tv_account_type_error) }
    private val mTvRemarkable by lazy { findViewById<TextView>(R.id.tv_remarkable) }
    private val mTvStandard by lazy { findViewById<TextView>(R.id.tv_standard) }
    private val mLlAccountType by lazy { findViewById<LinearLayout>(R.id.ll_account_type) }
    private val mTvAccountTypeTitle by lazy { findViewById<TextView>(R.id.tv_account_type_title) }
    private val mTvTradingPlatformError by lazy { findViewById<TextView>(R.id.tv_trading_platform_error) }
    private val mTvMt4Detail by lazy { findViewById<TextView>(R.id.tv_mt4_detail) }
    private val mLlMetaTrader4 by lazy { findViewById<LinearLayout>(R.id.ll_meta_trader_4) }
    private val mTvMt5Detail by lazy { findViewById<TextView>(R.id.tv_mt5_detail) }
    private val mLlMetaTrader5 by lazy { findViewById<LinearLayout>(R.id.ll_meta_trader_5) }
    private val mLlTradingPlatform by lazy { findViewById<LinearLayout>(R.id.ll_trading_platform) }
    private val mTvWithoutPlatform by lazy { findViewById<TextView>(R.id.tv_without_platform) }
    private val mTvTradingPlatformTitle by lazy { findViewById<TextView>(R.id.tv_trading_platform_title) }
    private val mTvAccountSettingsTitle by lazy { findViewById<TextView>(R.id.tv_account_settings_title) }

    private val mIvBack by lazy { findViewById<ImageView>(R.id.iv_step_back) }
    private val mIvStep by lazy { findViewById<ImageView>(R.id.iv_step) }
    private val mIvCustomer by lazy { findViewById<ImageView>(R.id.iv_customer) }
    private var mIsInitPlatform = true
    private var mIsShowLoading = false
    private var mPublicKeyStr: String = ""
    private var mPlatformResult: List<TradePlatform>? = null
    private var mGroupInfo: UserGroupInfo? = null
    private lateinit var mContainerSelectMap: MutableMap<ViewGroup, Int>
    private var mIsIb = false
    private var mSecondStepRequest: SecondStepRequest? = null
    private var mShowLeaveDialog = true

    @InjectPresenter
    private lateinit var mOpenPresenter: OpenAccountPresenter

    @InjectPresenter
    private lateinit var mCommonPresenter: CommonPresenter

    companion object {
        private const val PARAMS_SECOND_REQUEST = "params_second_request"
        private const val PARAMS_IS_IB = "params_is_ib"

        /**
         * 重复提交code
         */
        private const val REPEAT_SUBMIT_CODE = "MSUW0214"
        private const val PLATFORM_MT4 = 1

        private const val PLATFORM_MT5 = 2

        @JvmStatic
        fun startThis(context: Context) {
            Intent(context, ThirdStepOpenAccountActivity::class.java).apply {
                if (context !is Activity) {
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                }
                putExtra(PARAMS_IS_IB, false)
                context.startActivity(this)
            }
        }

        @JvmStatic
        fun startThis(context: Context, request: SecondStepRequest) {
            Intent(context, ThirdStepOpenAccountActivity::class.java).apply {
                if (context !is Activity) {
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                }
                putExtra(PARAMS_IS_IB, true)
                putExtra(PARAMS_SECOND_REQUEST, request)
                context.startActivity(this)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun obtainIntentData(intent: Intent) {
        super.obtainIntentData(intent)
        mSecondStepRequest = intent.serializable(PARAMS_SECOND_REQUEST)
        mIsIb = intent.getBooleanExtra(PARAMS_IS_IB, false)
    }

    override fun initLayout() = R.layout.activity_third_step_open_account

    override fun needShowLoading(): Boolean {
        return mIsShowLoading
    }

    override fun initView() {
        super.initView()
        initSelectMap()
    }

    private fun initSelectMap() {
        mContainerSelectMap = HashMap()
        mContainerSelectMap[mLlTradingPlatform] = -1
        mContainerSelectMap[mLlAccountType] = -1
        mContainerSelectMap[mLlAccountCurrency] = -1
    }

    private fun initTitleBar() {
        if (mIsIb) {
            mIvStep.setImageResource(R.drawable.ic_ib_step_2)
        } else {
            mIvStep.setImageResource(R.drawable.ic_step_3)
        }
    }

    override fun initLanguageText() {
        super.initLanguageText()
        mTvAccountSettingsTitle.text = DynamicResourceManager.getString(
            mContext, string.account_settings
        )
        mTvTradingPlatformTitle.text =
            DynamicResourceManager.getString(mContext, string.trading_platform)
        mTvMt5Detail.text = DynamicResourceManager.getString(mContext, string.premium_account)
        mTvMt4Detail.text = DynamicResourceManager.getString(mContext, string.basic_account)
        mTvWithoutPlatform.text = DynamicResourceManager.getString(string.no_platform_select)
        mTvAccountTypeTitle.text =
            DynamicResourceManager.getString(mContext, string.trading_account_type)
        mTvStandard.text = DynamicResourceManager.getString(mContext, string.standard)
        mTvRemarkable.text = DynamicResourceManager.getString(mContext, string.remarkable)
        mTvAccountCurrencyTitle.text =
            DynamicResourceManager.getString(mContext, string.account_currency)
        mTvWithoutCurrency.text = DynamicResourceManager.getString(string.no_currency_select)
        mTvTradingPasswordTitle.text =
            DynamicResourceManager.getString(mContext, string.trading_password)
        mEtTradingPassword.hint = DynamicResourceManager.getString(string.please_input)
        mTvConfirmTradingPasswordTitle.text =
            DynamicResourceManager.getString(mContext, string.confirm_trading_password)
        mEtConfirmTradingPassword.hint = DynamicResourceManager.getString(string.please_input)
        mTvAgreementText.text =
            DynamicResourceManager.getString(mContext, string.have_read_trading_agreement)
        val strAgreement =
            DynamicResourceManager.getString(mContext, string.trading_agreement_element)
        val replaceStr = strAgreement.replace("<ph1></ph1>", "Neex")
        mTvTradingAgreementElement.text = replaceStr
        ProtocolUtil.setAgreementHasTr(
            mTvTradingAgreementElement,
            replaceStr,
            color.color_7532FF,
            ProtocolUtil.TRADE_PRIVACY_POLICY_URL,
            isUnderlineText = false,
            isPdf = true
        )
        mBtnConfirm.text = DynamicResourceManager.getString(mContext, string.confirm)

    }

    override fun setListener() {
        super.setListener()
        mIvBack.setOnClickListener(this)
        mIvCustomer.setOnClickListener(this)
        setContainerChildListener(mLlTradingPlatform)
        setContainerChildListener(mLlAccountType)
        setContainerChildListener(mLlAccountCurrency)

        mIvShowTradingPassword.setOnClickListener(this)
        mIvClearTradingPassword.setOnClickListener(this)
        addTextChangeListener(mEtTradingPassword, mIvClearTradingPassword)
        addFocusChangeListener(mEtTradingPassword, mIvClearTradingPassword)

        mIvShowConfirmTradingPassword.setOnClickListener(this)
        mIvClearConfirmTradingPassword.setOnClickListener(this)
        addTextChangeListener(mEtConfirmTradingPassword, mIvClearConfirmTradingPassword)
        addFocusChangeListener(mEtConfirmTradingPassword, mIvClearConfirmTradingPassword)

        mIvAgreement.setOnClickListener(this)
        mBtnConfirm.setOnClickListener(this)
    }

    private fun updateInitView() {
        val widthPixels = mContext.resources.displayMetrics.widthPixels
        val dp16 = mContext.resources.getDimension(dimen.dp_16)
        val currencyWidth = (widthPixels - dp16 * 5) / 4
        mLlUsc.layoutParams.width = currencyWidth.toInt()
        mLlUsd.layoutParams.width = currencyWidth.toInt()
        mLlEur.layoutParams.width = currencyWidth.toInt()
        mLlGbp.layoutParams.width = currencyWidth.toInt()
        mTvTradingPasswordError.autoSize(
            mContext.resources.getDimension(dimen.sp_8).toInt(),
            mContext.resources.getDimension(dimen.sp_10).toInt()
        )
        mTvConfirmTradingPasswordError.autoSize(
            mContext.resources.getDimension(dimen.sp_8).toInt(),
            mContext.resources.getDimension(dimen.sp_10).toInt()
        )
        mBtnConfirm.isEnabled = false
    }

    override fun setView() {
        super.setView()
        mIvAgreement.expandTouchArea()
        hideTitleBar()
        initTitleBar()
        updateInitView()
        loadData()
    }

    override fun loadData() {
        super.loadData()
        GlobalInfoManager.getInstance().addListener(this)
        getPublicKey()
        getSystemUserInfo()
    }

    private fun getSystemUserInfo() {
        GlobalInfoManager.getInstance().update(GlobalInfoManager.UPDATE_USR_INFO)
    }

    private fun getPublicKey() {
        val publicKeyStr = GlobalInfoManager.getInstance().getPublicKeyStr()
        if (!TextUtils.isEmpty(publicKeyStr)) {
            mPublicKeyStr = publicKeyStr
        } else {
            GlobalInfoManager.getInstance().update(GlobalInfoManager.UPDATE_PUBLIC_KEY)
        }
    }

    private fun queryPlatform(invitationCode: String) {
        val userToken = GlobalInfoManager.getInstance().getUserToken()
        mIsShowLoading = false
        mCommonPresenter.queryPlatform(userToken, invitationCode)
    }

    private fun queryGroupInfo(invitationCode: String) {
        val userToken = GlobalInfoManager.getInstance().getUserToken()
        mIsShowLoading = false
        mCommonPresenter.queryGroupAndCurrency(userToken, invitationCode)
    }

    private fun queryAccountType(invitationCode: String) {
        val userToken = GlobalInfoManager.getInstance().getUserToken()
        mIsShowLoading = false
        mCommonPresenter.queryAccountType(userToken, invitationCode)
    }


    private fun setContainerChildListener(layout: ViewGroup) {
        for (index in 0 until layout.childCount) {
            layout.getChildAt(index)?.also { childView ->
                childView.setOnClickListener {
                    if (!Utils.isFastDoubleClick(childView.id)) {
                        //不允许选中之后，取消选中
                        if (!childView.isSelected) {
                            doClick(childView)
                            childView.isSelected = !childView.isSelected
                            setChildTextSelect(childView)
                            removeOtherSelect(childView, layout)
                            mContainerSelectMap[layout] = index
                            checkButtonEnable()
                        }
                    }
                }
            }
        }
    }

    private fun setChildTextSelect(childView: View) {
        if (childView is ViewGroup) {
            for (i in 0 until childView.childCount) {
                val view = childView.getChildAt(i)
                if (view is TextView) {
                    view.isSelected = true
                }
            }
        }
    }

    private fun removeChildTextSelect(childView: View) {
        if (childView is ViewGroup) {
            for (i in 0 until childView.childCount) {
                val view = childView.getChildAt(i)
                if (view is TextView) {
                    view.isSelected = false
                }
            }
        }
    }

    private fun checkButtonEnable() {
        if (!mContainerSelectMap.containsValue(-1)) {
            if (checkInputWithoutTip(mEtTradingPassword) && checkInputWithoutTip(
                    mEtConfirmTradingPassword
                ) && TextUtils.equals(
                    mEtTradingPassword.text, mEtConfirmTradingPassword.text
                ) && mIvAgreement.isSelected
            ) {
                mBtnConfirm.isEnabled = true
                return
            }
        }
    }

    private fun removeOtherSelect(jumpView: View, layout: ViewGroup) {
        for (i in 0 until layout.childCount) {
            layout.getChildAt(i)?.also { childView ->
                if (childView.id != jumpView.id) {
                    childView.isSelected = false
                    removeChildTextSelect(childView)
                }
            }
        }
    }

    private fun addTextChangeListener(editText: EditText, clearView: ImageView? = null) {
        editText.addTextChangedListener { text ->
            if (text.toString().contains(" ")) {
                val str = text?.toString()?.split(" ")
                val sb = StringBuffer()
                for (i in 0 until str?.size!!) {
                    sb.append(str[i])
                }
                editText.setText(sb.toString())
                editText.setSelection(sb.toString().length)
            }
            setClearView(editText.text, clearView)
            checkButtonEnable()
            if (editText == mEtConfirmTradingPassword) {
                if (checkInput(editText)) {
                    checkPasswordEquals()
                }
            } else if (editText == mEtTradingPassword) {
                if (!TextUtils.isEmpty(mEtConfirmTradingPassword.text) && checkInput(
                        mEtConfirmTradingPassword
                    )
                ) {
                    checkPasswordEquals()
                }
            }
        }
    }


    private fun addFocusChangeListener(
        editText: EditText, clearView: ImageView? = null
    ) {
        editText.setOnFocusChangeListener { _, hasFocus ->
            if (hasFocus) {
                //去除错误边框展示
                editText.isSelected = false
                setClearView(editText.text, clearView)
            } else {
                clearView?.visibility = View.GONE
                if (checkInput(editText)) {
                    if (mEtConfirmTradingPassword == editText) {
                        checkPasswordEquals()
                    }
                }
            }
        }
    }

    private fun setClearView(text: Editable?, clearView: ImageView?) {
        if (!TextUtils.isEmpty(text)) {
            clearView?.visibility = View.VISIBLE
        } else {
            clearView?.visibility = View.GONE
        }
    }

    private fun checkInputWithoutTip(editText: EditText): Boolean {
        when (editText) {
            mEtTradingPassword -> return CheckInputUtil.checkInputWithoutTip(
                mEtTradingPassword.text.toString(), RegexUtils.TRADE_PASSWORD_REGEX
            )

            mEtConfirmTradingPassword -> return CheckInputUtil.checkInputWithoutTip(
                mEtConfirmTradingPassword.text.toString(), RegexUtils.TRADE_PASSWORD_REGEX
            )
        }
        return true
    }

    private fun checkInput(editText: EditText): Boolean {
        when (editText) {
            mEtTradingPassword -> return CheckInputUtil.checkInput(
                mEtTradingPassword.text.toString(),
                RegexUtils.TRADE_PASSWORD_REGEX,
                mEtTradingPassword,
                mTvTradingPasswordError,
                string.password_empty,
                string.password_regular_tip
            )

            mEtConfirmTradingPassword -> return CheckInputUtil.checkInput(
                mEtConfirmTradingPassword.text.toString(),
                RegexUtils.TRADE_PASSWORD_REGEX,
                mEtConfirmTradingPassword,
                mTvConfirmTradingPasswordError,
                string.password_empty,
                string.password_regular_tip
            )
        }
        return true
    }

    private fun checkPasswordEquals() {
        if (!TextUtils.equals(
                mEtTradingPassword.text, mEtConfirmTradingPassword.text
            )
        ) {
            mTvConfirmTradingPasswordError.visibility = View.VISIBLE
            mTvConfirmTradingPasswordError.text =
                DynamicResourceManager.getString(string.trading_password_inconsistency)
        } else {
            mTvConfirmTradingPasswordError.visibility = View.INVISIBLE
        }
    }

    private fun hidePasswordText(editText: EditText, showValueView: ImageView) {
        showValueView.isSelected = false
        showValueView.setImageResource(drawable.icon_eye_off)
        editText.transformationMethod = PasswordTransformationMethod.getInstance()
        editText.setSelection(editText.text.length)
    }

    private fun showPasswordText(editText: EditText, showValueView: ImageView) {
        showValueView.isSelected = true
        showValueView.setImageResource(drawable.icon_eye_on)
        editText.transformationMethod = HideReturnsTransformationMethod.getInstance()
        editText.setSelection(editText.text.length)
    }


    override fun doClick(v: View?) {
        super.doClick(v)
        when (v?.id) {
            R.id.iv_step_back -> {
                if (mShowLeaveDialog) {
                    showLeaveDialog()
                } else {
                    gotoMain()
                }
            }

            R.id.iv_customer -> {
                ToastUtils.longToast(
                    DynamicResourceManager.getString(
                        mContext, string.developing
                    )
                )
            }

            R.id.ll_meta_trader_4, R.id.ll_meta_trader_5 -> {
                //根据平台获取币种
                updateCurrency(v.tag.toString())
            }

            R.id.iv_show_trading_password -> {
                if (mIvShowTradingPassword.isSelected) {
                    hidePasswordText(mEtTradingPassword, mIvShowTradingPassword)
                } else {
                    showPasswordText(mEtTradingPassword, mIvShowTradingPassword)
                }
            }

            R.id.iv_show_confirm_trading_password -> {
                if (mIvShowConfirmTradingPassword.isSelected) {
                    hidePasswordText(mEtConfirmTradingPassword, mIvShowConfirmTradingPassword)
                } else {
                    showPasswordText(mEtConfirmTradingPassword, mIvShowConfirmTradingPassword)
                }
            }

            R.id.iv_clear_trading_password -> mEtTradingPassword.setText("")
            R.id.iv_clear_confirm_trading_password -> mEtConfirmTradingPassword.setText("")

            R.id.iv_agreement -> {
                mIvAgreement.isSelected = !mIvAgreement.isSelected
                checkButtonEnable()
            }

            R.id.btn_confirm -> {
                submit()
            }
        }
    }

    /**
     * 屏蔽物理返回键
     */
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return if (keyCode == KeyEvent.KEYCODE_BACK) {
            true
        } else super.onKeyDown(keyCode, event)
    }

    private fun submit() {
        if (!mIsIb) {
            submitRc()
        } else {
            submitIb()
        }
    }

    private fun submitIb() {
        getIbRequest()?.also { request ->
            val userToken = GlobalInfoManager.getInstance().getUserToken()
            mIsShowLoading = true
            mOpenPresenter.submitIBThirdStep(userToken, request)
        }
    }


    private fun submitRc() {
        getRequest()?.also { request ->
            val userToken = GlobalInfoManager.getInstance().getUserToken()
            mIsShowLoading = true
            mOpenPresenter.submitRCThirdStep(userToken, request)
        }
    }

    private fun getIbRequest(): ThirdStepIbRequest? {
        if (mSecondStepRequest == null) {
            return null
        }
        val thirdStepRequest = getRequest() ?: return null
        val thirdStep = mSecondStepRequest!!.fullThirdStep()
        thirdStep.full(thirdStepRequest)
        return thirdStep
    }

    private fun getRequest(): ThirdStepRequest? {
        var request: ThirdStepRequest? = ThirdStepRequest()
        for (entry in mContainerSelectMap) {
            val container = entry.key
            val selectIndex = entry.value
            if (selectIndex == -1) {
                request = null
                return request
            }
            container.getChildAt(selectIndex)?.also { view ->
                LogUtils.d("getRequestBean  view->${view}  tag-->${view.tag}")
                when (container) {
                    //财富来源
                    mLlTradingPlatform -> request!!.platform = view.tag.toString()
                    mLlAccountType -> request!!.accountType = view.tag.toString()
                    mLlAccountCurrency -> request!!.accountCoinType = view.tag.toString()
                }
            }
        }
        if (!checkInput(mEtTradingPassword) || !checkInput(mEtConfirmTradingPassword) || !TextUtils.equals(
                mEtTradingPassword.text, mEtTradingPassword.text
            ) || TextUtils.isEmpty(mPublicKeyStr)
        ) {
            request = null
            return request
        }
        SignUtils.encrypt(
            SignUtils.loadPublicKeyByStr(mPublicKeyStr),
            mEtTradingPassword.text.toString().toByteArray()
        )?.also {
            request!!.accNum01Password = it
        }
        SignUtils.encrypt(
            SignUtils.loadPublicKeyByStr(mPublicKeyStr),
            mEtConfirmTradingPassword.text.toString().toByteArray()
        )?.also {
            request!!.confirmPassword = it
        }
        return request
    }

    private fun updateCurrency(platform: String) {
        val systemUserInfo = GlobalInfoManager.getInstance().getSystemUserInfo()
        val userToken = GlobalInfoManager.getInstance().getUserToken()
        systemUserInfo?.also { user ->
            mIsShowLoading = false
            mCommonPresenter.queryCurrency(
                userToken, user.residence, platform, tradeType = "1"
            )
        }
    }


    private fun showLeaveDialog() {
        val dialog = CustomTipDialog(mContext)
        dialog.setTopRes(R.drawable.ic_circle_warning)
            .setTitle(DynamicResourceManager.getString(mContext, string.confirm_leave))
            .setCancelText(
                DynamicResourceManager.getString(
                    mContext, string.cancel
                )
            ).setConfirmText(
                DynamicResourceManager.getString(
                    mContext, string.confirm
                )
            ).setCallBack { confirm ->
                if (confirm) {
                    gotoMain()
                }
                dialog.dismiss()
            }.show()
    }

    private fun gotoMain() {
        ARouter.getInstance().build(RouterPath.UFUFMainStandardActivityInfo.PATH).navigation()
        finish()
    }

    /**
     * 根据邀请码查询上级所属组与币种
     */
    override fun handleGroupCurrencyView(response: ResponseResult<UserGroupInfo>) {
        if (response.code == ResponseResult.SUCCESS_CODE) {
            response.data?.also {
                mGroupInfo = it
                checkDefaultSelectPlatform()
            }
        } else {
            LogUtils.d(
                ThirdStepOpenAccountActivity::class.java.simpleName,
                "handleGroupCurrencyView error->$response"
            )
        }
    }

    /**
     * 获取系统的平台列表
     */
    override fun handlePlatformView(response: ResponseResult<List<TradePlatform>>) {
        if (response.code == ResponseResult.SUCCESS_CODE) {
            response.data?.also {
                mPlatformResult = it
                checkDefaultSelectPlatform()
            }
        } else {
            LogUtils.d(
                ThirdStepOpenAccountActivity::class.java.simpleName,
                "handlePlatformView error->$response"
            )
        }
    }

    /**
     * 获取当前平台所支持的币种列表
     */
    override fun handleCurrencyView(response: ResponseResult<List<String>>) {
        if (response.code == ResponseResult.SUCCESS_CODE) {
            response.data?.also {
                updateCurrencyUI(it)
            }
        } else {
            LogUtils.d(
                ThirdStepOpenAccountActivity::class.java.simpleName,
                "handleCurrencyView error->$response"
            )
        }
    }

    /**
     * 获取支持的账户类型
     */
    override fun handleAccountTypeView(response: ResponseResult<List<Int>>) {
        if (response.code == ResponseResult.SUCCESS_CODE) {
            response.data?.also { list ->
                if (list.isNotEmpty()) {
                    updateTradeAccountType(list)
                }
            }
        } else {
            LogUtils.d(
                ThirdStepOpenAccountActivity::class.java.simpleName,
                "handleAccountTypeView error->$response"
            )
        }
    }

    private fun updateTradeAccountType(list: List<Int>) {
        mTvStandard.visibility = View.GONE
        mTvRemarkable.visibility = View.GONE
        for (type in list) {
            if (type == TradeAccountType.ECN.type) {
                mTvRemarkable.visibility = View.VISIBLE
            } else if (type == TradeAccountType.STP.type) {
                mTvStandard.visibility = View.VISIBLE
            }
        }
    }

    private fun checkDefaultSelectPlatform() {
        LogUtils.d(
            "ThirdStepOpenAccountActivity",
            "checkDefaultSelectPlatform mPlatformResult-->$mPlatformResult"
        )
        LogUtils.d(
            "ThirdStepOpenAccountActivity", "checkDefaultSelectPlatform mGroupInfo-->$mGroupInfo"
        )
        if (mPlatformResult != null && mGroupInfo != null) {
            //首先根据mGroupInfo中的platform展示
            if (mGroupInfo!!.platform != null) {
                when (mGroupInfo!!.platform) {
                    PLATFORM_MT4 -> {
                        mLlMetaTrader4.visibility = View.VISIBLE
                        mLlMetaTrader5.visibility = View.GONE
                    }

                    PLATFORM_MT5 -> {
                        mLlMetaTrader5.visibility = View.VISIBLE
                        mLlMetaTrader4.visibility = View.GONE
                    }
                }
            } else {
                //如果 platform为null,并且 platformLimit为true,展示暂无平台可选
                if (mGroupInfo!!.platformLimit) {
                    mLlMetaTrader4.visibility = View.GONE
                    mLlMetaTrader5.visibility = View.GONE
                } else {
                    //展示mPlatformResult中的交易平台
                    mLlMetaTrader4.visibility = View.GONE
                    mLlMetaTrader5.visibility = View.GONE
                    for (platform in mPlatformResult!!) {
                        if (platform.platform == PLATFORM_MT4) {
                            mLlMetaTrader4.visibility = View.VISIBLE
                        }
                        if (platform.platform == PLATFORM_MT5) {
                            mLlMetaTrader5.visibility = View.VISIBLE
                        }
                    }
                }
            }
            LogUtils.d(
                "ThirdStepOpenAccountActivity",
                "mLlTradingPlatform.childCount--->${mLlTradingPlatform.childCount}}"
            )
            if (mLlMetaTrader4.isShown || mLlMetaTrader5.isShown) {
                mLlTradingPlatform.visibility = View.VISIBLE
                mTvWithoutPlatform.visibility = View.GONE
            } else {
                mLlTradingPlatform.visibility = View.GONE
                mTvWithoutPlatform.visibility = View.VISIBLE
                //如果平台展示暂无平台选择，则展示暂无币种选择
                updateCurrencyUI(emptyList())
            }
            //默认选中MT5
            if (mLlMetaTrader5.isShown) {
                mLlMetaTrader5.performClick()
                return
            }
            //如果Mt5没有展示，默认选中mt4
            if (mLlMetaTrader4.isShown) {
                mLlMetaTrader4.performClick()
            }
        }
    }


    private fun updateCurrencyUI(list: List<String>) {
        //没有值展示暂无币种选择
        if (list.isEmpty()) {
            mLlAccountCurrency.visibility = View.GONE
            mTvWithoutCurrency.visibility = View.VISIBLE
            return
        }
        //currency没有值并且currencyLimit为true,展示暂无币种可选
        mGroupInfo?.also {
            if (TextUtils.isEmpty(it.currency) && it.currencyLimit == true) {
                mLlAccountCurrency.visibility = View.GONE
                mTvWithoutCurrency.visibility = View.VISIBLE
                return
            }
        }

        //currency与list进行取交集展示币种
        mLlUsc.visibility = View.GONE
        mLlUsd.visibility = View.GONE
        mLlEur.visibility = View.GONE
        mLlGbp.visibility = View.GONE
        var currency = mGroupInfo!!.currency
        if (TextUtils.isEmpty(mGroupInfo!!.currency)) {
            if (mGroupInfo!!.currencyLimit == null || mGroupInfo!!.currencyLimit == false) {
                for (item in list) {
                    currency = item
                    checkShowCurrency(currency, list)
                }
            }
        } else {
            checkShowCurrency(currency, list)
        }
        //如果已经被选择的币种，不可选，则重置其选中状态
        val index = mContainerSelectMap[mLlAccountCurrency] ?: -1
        if (index != -1) {
            mLlAccountCurrency.getChildAt(index)?.also { view ->
                if (!view.isShown) {
                    mContainerSelectMap[mLlAccountCurrency] = -1
                    removeChildTextSelect(view)
                }
            }
        }
        //如果交际为空，展示暂无币种展示
        if (mLlUsc.isShown || mLlUsd.isShown || mLlEur.isShown || mLlGbp.isShown) {
            mLlAccountCurrency.visibility = View.VISIBLE
            mTvWithoutCurrency.visibility = View.GONE
        } else {
            mLlAccountCurrency.visibility = View.GONE
            mTvWithoutCurrency.visibility = View.VISIBLE
        }
    }

    private fun checkShowCurrency(currency: String, list: List<String>) {
        when (currency) {
            USC -> {
                if (list.contains(currency)) {
                    mLlUsc.visibility = View.VISIBLE
                }
            }

            USD -> {
                if (list.contains(currency)) {
                    mLlUsd.visibility = View.VISIBLE
                }
            }

            EUR -> {
                if (list.contains(currency)) {
                    mLlEur.visibility = View.VISIBLE
                }
            }

            GBP -> {
                if (list.contains(currency)) {
                    mLlGbp.visibility = View.VISIBLE
                }
            }
        }
    }

    /**
     * 第三步提交之后的返回结果
     */
    override fun handleThirdStep(response: ResponseResult<Any?>) {
        if (response.code == ResponseResult.SUCCESS_CODE) {
            updateResult()
        } else if (response.code == REPEAT_SUBMIT_CODE) {
            response.toast()
            mShowLeaveDialog = false
        } else {
            LogUtils.d(
                ThirdStepOpenAccountActivity::class.java.simpleName,
                "handleThirdStep error->$response"
            )
            response.toast()
        }
    }

    private fun updateResult() {
        mIsShowLoading = true
        showLoading()
        //更新SystemUserInfo
        GlobalInfoManager.getInstance().update(GlobalInfoManager.UPDATE_USR_INFO)
    }


    override fun onUpdate(obj: Any?) {
        if (obj is String) {
            mPublicKeyStr = obj
        } else if (obj is SystemUserInfo) {
            if (mIsInitPlatform) {
                //根据有效的邀请码，获取平台信息
                queryGroupInfo(obj.invitationCode ?: "")
                queryPlatform(obj.invitationCode ?: "")
                queryAccountType(obj.invitationCode ?: "")
                mIsInitPlatform = false
            } else {
                mIsShowLoading = false
                hideLoading()
                gotoResult()
            }
        }
    }


    private fun gotoResult() {
        ResultOfOpenAccountActivity.startThis(mContext)
        finish()
    }

    override fun onDestroy() {
        GlobalInfoManager.getInstance().remove(this)
        super.onDestroy()
    }


}